import React from "react";
import "./SearchBox.css";

class SearchBox extends React.Component{
  constructor(props){
    super(props)
    this.state = {
      isShow:false,
      history:[
        "123",
        "456",
        "789",
        "101",
        "102",
        "103"
      ],
      hoverIndex:-1,
      // selectIndex:-1,
      value:""
    }
  }

  render(){
    return(
      <div>
        <input  type="text" 
        placeholder={this.props.placeholder}
        ref="input"
        value={this.state.value}
        onFocus={()=>{
          //react修改state 必须要调用setState函数
          //调用setState函数修改组件状态后，组件的render函数会被重新调用
          this.setState({
            isShow:true
          })
        }}
        onBlur={()=>{
          this.setState({
            isShow:false
          })
        }}
        onKeyDown={(event)=>{
          if(event.keyCode === 13){
            var value = this.refs.input.value;
            this.props.sendMessage(value)
          }else if(event.keyCode===40){
            //键盘下键
            this.state.hoverIndex++;
            if(this.state.hoverIndex > this.state.history.length-1){
              this.state.hoverIndex = 0;
            }


          }else if(event.keyCode === 38){
            this.state.hoverIndex --;
            if(this.state.hoverIndex < 0){
              this.state.hoverIndex = this.state.history.length-1
            }
          }

          this.setState({
            value:this.state.history[this.state.hoverIndex],
            hoverIndex:this.state.hoverIndex
          })
        }}/>
        <div className={this.state.isShow?"search_history":"search_history_hidden"}>
          {
            this.state.history.map((element,index)=>{
              return <div className={this.state.hoverIndex===index?'history_hover history_item':'history_item'}
              onMouseEnter={()=>{
                this.setState({
                  hoverIndex:index
                })
              }}>
                <div>{element}</div>
                <button className={this.state.hoverIndex===index?"button_show":"button_hidden"}>删除</button>
              </div>
            })
          }
        </div>
      </div>
    );
  }

}

export default SearchBox;